/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class SplitBDFFileIntoChunks {
    public static void main(String[] args) {
        // BDF 文件路径
        String filePath = "E:\\要素数据库\\结构CAE交付\\C919_10002\\C919_Material_Library.bdf";

        try {
            // 读取 BDF 文件内容并逐行处理
            processBDFFile(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void processBDFFile(String filePath) throws IOException {
        // 需要处理的行类型
        List<String> typesToProcess = Arrays.asList("CQUAD4", "GRID", "PSHELL", "MAT1", "MAT8", "MAT9");

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String currentLine;
            while ((currentLine = br.readLine()) != null) {
                // 检查行是否以指定类型开头
                for (String type : typesToProcess) {
                    if (currentLine.startsWith(type)) {
                        // 分割字符串
                        String[] chunks = splitStringIntoChunks(currentLine, 8, type);
                        System.out.println(Arrays.stream(chunks).toList());
                        // 打印结果
//                        for (String chunk : chunks) {
//                            System.out.println(type + " " + chunk);
//                        }
                        break;
                    }
                }
            }
        }
    }

    public static String[] splitStringIntoChunks(String s, int chunkSize, String type) {
        // 去除开头的类型部分
//        if (type.equals("GRID") || type.equals("MAT1") || type.equals("MAT8") || type.equals("MAT9")) {
//            s = s.replaceFirst(type + "    ", ""); // 保留四个空格
//        } else {
//            s = s.replaceFirst(type + "  ", ""); // 保留两个空格
//        }
        String typk = type + " ".repeat(8 - type.length());
        s = s.replaceFirst(typk, "");

        // 计算需要的分组数量
        int numChunks = (int) Math.ceil((double) s.length() / chunkSize);

        // 创建分组数组
        String[] chunks = new String[numChunks + 1];
        // 第一个元素包含类型前缀
        chunks[0] = type;

        // 按每8位进行分割
        for (int i = 0; i < numChunks; i++) {
            int start = i * chunkSize;
            int end = Math.min(start + chunkSize, s.length());
            chunks[i + 1] = s.substring(start, end).trim();
        }

//        // 按每8位进行分割
//        for (int i = 0; i < numChunks; i++) {
//            int start = i * chunkSize;
//            int end = Math.min(start + chunkSize, s.length());
//            chunks[i] = s.substring(start, end);
//        }

        return chunks;
    }
}
